<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\RoomsResource;
use App\Models\Consume;
use App\Models\Episode;
use App\Models\History;
use App\Models\Type;
use App\Models\Video;
use Illuminate\Support\Facades\Validator;
use App\Models\Room;
use Illuminate\Http\Request;

class EpisodesController extends Controller
{
    /***
     *通过分类获取剧集列表
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request,Episode $episode)
    {
        $query=$episode->newQuery();
        if($request->has('type') && !empty($request->type)){
            $query->whereJsonContains('type_id',$request->type);
        }
        $list=$query->where('status',1)
            ->orderBy('sort')
            ->select('id', 'name', 'blues', 'cover', 'cover_crosswise')
            ->paginate(10);
        if($list->isEmpty()){
            return $this->error('数据查询为空');
        }
        foreach ($list as &$value){
            $value['cover']=dealUrl($value['cover']);
            $value['cover_crosswise'] = dealUrl($value['cover_crosswise']);
            $video_id = History::where('user_id', $this->user->id)->where('traces_id', $value['id'])->max('video_id');
            $looking = Video::where('id', $video_id)->value('sort');
            $value['looking'] = empty($looking) ? 0 : $looking;
        }
        return $this->success('success',$list);
    }


    /***
     *单个剧集详情
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request,Episode $episode)
    {
        $query=$episode->newQuery();
        if($request->has('id') && !empty($request->id)){
            $query->where('id',$request->id);
        }
        $list=$query->where('status',1)
            ->orderBy('sort')
            ->select('id','name','blues','cover')
            ->first();
        if(!$list){
            return $this->error('数据查询为空');
        }
        $video=Video::where('episodes_id',$list['id'])
            ->where('status', 1)
            ->orderBy('sort')
            ->select('id','name','is_fee','cover','sort','price')
            ->get()->each(function (&$item) use ($list) {
                $item->cover=dealUrl($item->cover);
                $item->url=dealUrl($item->url);
                $is_pay = Consume::where(['user_id' => $this->user->id, 'video_id' => $list['id'], 'sort' => $item['sort']])->exists() ? 1 : 0;
                if ($item['is_fee'] == 1 && !$is_pay) {
                    $item->is_lock = 1;
                } else {
                    $item->is_lock = 0;
                }
            })->toArray();

        $list['cover']=dealUrl($list['cover']);
        $list['videolist']=$video;
        $list['uplist']=Video::where('episodes_id',$list['id'])->max('sort');
        return $this->success('success',$list);
    }


}
